<?php

namespace App\Http\Middleware;

use App\Models\ChinaBank\UserModel;
use Closure;
use Illuminate\Http\Request;
use Overtrue\LaravelWeChat\Facade as EasyWeChat;

class WXLogin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        //检查是否微信登录

        $url = $request->path();
        $excepts = [""];
        $WXAUTH = $request->session()->get("WXAUTH");

        //如果没有进行微信登录，
        if(is_null($WXAUTH) && !in_array($url,$excepts)){

            //检查是否是获取code过程中

            $wxloging   = $request->session()->get('wxloging');
            $officialAccount = EasyWeChat::officialAccount();

            if(!$wxloging){
                //跳转到授权页面

                //将当前信息存储起来
                $request->session()->put("lastDataInfo",$request->all());
                $request->session()->put("wxloging",true);
                $request->session()->save();

                $authUrl = $request->url();
                $authUrl = str_replace(":800","",$authUrl);
                $response = $officialAccount->oauth->scopes(['snsapi_userinfo'])->redirect($authUrl);
                return $response;

            }elseif($wxloging){

                //情况正在登录标记
                $request->session()->forget("wxloging");

                //获取微信信息
                $wxinfo = $officialAccount->oauth->user();
                $userInfo = [
                    'openid'    => $wxinfo->getId(),
                    'head'      => $wxinfo->getAvatar(),
                    'wxname'    => $wxinfo->getName()
                ];
                $userInfo = UserModel::wxRegister($userInfo);

                $request->session()->put('USER',$userInfo);
                $request->session()->put('userId',$userInfo->user_id);

                //将历史数据加到请求头，返回到业务路径
                $data = $request->session()->get('lastDataInfo');
                foreach($data as $key => $v)
                {
                    $request->offsetSet($key,$v);
                }

                $request->session()->put("WXAUTH",true); //标识是否已经微信授权的关键
            }
        }
        return $next($request);
    }

    public function log($msg)
    {
        file_put_contents("log.txt",$msg."\n",FILE_APPEND);
    }
}
